import { Page } from '@/base/Page';
import {deleteMember, getNewsMemberList} from '@/base/api/MemberApi';
import { Member } from '@/base/model/Member';
import { isEmpty } from '@/base/util/Strings';
import {getAgentList} from '@/base/api/AgentApi';
import {Agent} from '@/base/model/Agent';
import {MemberNews} from '@/base/model/MemberNews';
import {Company} from "@/base/model/Company";
import {getCompanyList} from "@/base/api/CompanyApi";

class Form {
  phone = '';
  companyId = [];
}

export class ListBloc {
  form = new Form();

  paged: Page<MemberNews> = new Page<MemberNews>([], 0, 1, 15, 0, []);
  angent: Page<Agent> = new Page<Agent>([], 0, 1, 15, 0, []);
  companyPage: Page<Company> = new Page<Company>([], 0, 1, 15, 0, []);

  loading = false;
  sortList: any = [];
  companyList: any = [];
  newsId: string | null = '';

  load(pageIndex: number, pageSize: number) {
    this.loading = true;
    return getNewsMemberList({
      pageIndex,
      pageSize,
      phone: this.form.phone,
      // createBegin: this.form.createBegin,
      // createEnd: this.form.createEnd,
      companyId: this.form.companyId,
      newsId: this.newsId
    }).then((res) => {
      this.paged = res.data;
    }).finally(() => {
      this.loading = false;
    });
  }
  getAgentList(pageIndex: number, pageSize: number, sortDirection: string) {
    this.loading = true;
    return getAgentList({
      pageIndex: this.angent.pageIndex,
      pageSize: 1000,
      sortDirection: 'ESC'
    }).then((res) => {
      this.sortList = res.data.items.map(function (item) {
        var obj = {id: 0, agentName: ''};
        // @ts-ignore
        obj.id = item.id;
        obj.agentName = item.agentName;
        return obj;
      });
      return this.sortList;
    }).finally(() => {
      this.loading = false;
    });
  }
  getCompanyList(pageIndex: number, pageSize: number, sortDirection: string) {
    this.loading = true;
    return getCompanyList({
      pageIndex: 1,
      pageSize: 50,
      sortDirection: 'ASC'
    }).then((res) => {
      this.companyList = res.data.items.map(function (item) {
        var obj = {id: 0, name: ''};
        // @ts-ignore
        obj.id = item.id;
        obj.name = item.name;
        return obj;
      });
      return this.companyList;
    }).finally(() => {
      this.loading = false;
    });
  }
  removeItem(dateItem: Member) {
    this.loading = true;
    return deleteMember(dateItem.id)
      .finally(() => {
        this.loading = false;
      });
  }

  reset() {
    this.form.phone = '';
    this.paged.pageIndex = 1;
    this.paged.pageSize = 15;
    this.form.companyId = [];
    this.load(this.paged.pageIndex, this.paged.pageSize);
  }

  getCompanyName(companyId: number) {
    const item = this.companyList.find(x => x.id === companyId);
    return item == null ? '' : item.name;
  }
  getAgentName(agentId: number) {
    const item = this.sortList.find(x => x.id === agentId);
    return item == null ? '' : item.agentName;
  }
}
